# -*- coding: utf-8 -*-

from odoo import models, fields, api


class CpqConfigurationLine(models.Model):
    _name = 'cpq.configuration.line'
    _description = '配置项明细'
    _order = 'sequence, id'
    
    # ============ 基础信息 ============
    config_id = fields.Many2one(
        'cpq.configuration',
        string='配置器',
        required=True,
        ondelete='cascade'
    )
    
    sequence = fields.Integer(
        string='序号',
        default=10
    )
    
    # ============ 配置属性 ============
    attribute_id = fields.Many2one(
        'product.attribute',
        string='属性',
        required=True
    )
    
    value_id = fields.Many2one(
        'product.attribute.value',
        string='属性值',
        required=True,
        domain="[('attribute_id', '=', attribute_id)]"
    )
    
    # ============ 约束 ============
    is_required = fields.Boolean(
        string='必选',
        default=False
    )
    
    is_valid = fields.Boolean(
        string='有效',
        default=True,
        help='配置项是否满足所有规则约束'
    )
    
    depends_on_ids = fields.Many2many(
        'cpq.configuration.line',
        'cpq_config_line_dependency_rel',
        'line_id',
        'depends_on_id',
        string='依赖项'
    )
    
    # ============ 成本影响 ============
    cost_impact = fields.Monetary(
        string='成本影响',
        currency_field='currency_id',
        help='选择该项增加或减少的成本'
    )
    
    currency_id = fields.Many2one(
        'res.currency',
        related='config_id.currency_id',
        string='货币'
    )
    
    # ============ BOM关联 ============
    bom_component_id = fields.Many2one(
        'product.product',
        string='BOM组件',
        help='该配置项对应的物料'
    )
    
    component_quantity = fields.Float(
        string='组件数量',
        default=1.0,
        digits='Product Unit of Measure'
    )
    
    # ============ 备注 ============
    description = fields.Text(
        string='描述'
    )
    
    notes = fields.Text(
        string='备注'
    )
    
    # ============ 约束 ============
    @api.constrains('attribute_id', 'value_id')
    def _check_attribute_value(self):
        """检查属性值是否属于该属性"""
        for record in self:
            if record.value_id.attribute_id != record.attribute_id:
                raise ValidationError(f'属性值 {record.value_id.name} 不属于属性 {record.attribute_id.name}')
    
    # ============ Onchange ============
    @api.onchange('value_id')
    def _onchange_value_id(self):
        """当属性值改变时，检查成本影响"""
        # TODO: 可以从预设的成本表中获取成本影响
        pass

